package com.xzjt.common.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import org.apache.shiro.crypto.hash.SimpleHash;

/**
 * @ClassName: PasswordUtils
 * @User: yuand
 * @Date: 2021/10/30 12:04

 */
public class PasswordUtils {

    // 密码加密次数
    private static final int hashIterations = 1024;
    // 密码加密方式
    private static final String hashAlgorithmName = "MD5";
    // 密码盐值位数
    private static final int saltNum = 8;

    /**
     * 密码加密
     *
     * @param password 明文密码
     * @param salt     盐值
     * @return
     */
    public static String encodePassword(String password, String salt) {
        Object simpleHash = new SimpleHash(hashAlgorithmName, password, salt, hashIterations);
        return simpleHash.toString();
    }

    /**
     * 密码校验
     *
     * @param inputPassword 输入密码
     * @param salt          盐值
     * @param dbPassword    数据库密码
     * @return
     */
    public static boolean verify(String inputPassword, String salt, String dbPassword) {
        String encodePassword = encodePassword(inputPassword, salt);
        return encodePassword.equals(dbPassword);
    }

    /**
     * 随机生成加密密码盐值
     *
     * @return
     */
    public static String generateSalt() {
        return RandomUtils.randomString(saltNum);
    }

    /**
     * MD5加密
     *
     * @param str
     * @return
     */
    public static String toMd5(String str) {
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        return md5.digestHex(str);
    }

    /**
     * 字符串转Base64
     *
     * @param str
     * @return
     */
    public static String encodeBase64(String str) {
        return Base64.encode(str);
    }

    /**
     * 验证密码必须是数字加大小写字母16位
     *
     * @param pwd
     * @return
     */
    public static boolean checkPwd(String pwd) {
        String regExp = "^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{6,16}$";
        if (pwd.matches(regExp)) {
            return true;
        }
        return false;
    }

    /**
     * Base64解码
     *
     * @param str
     * @return
     */
    public static String decodeBase64(String str) {
        return Base64.decodeStr(str);
    }

    public static void main(String[] args) {
        String salt = "zs";
        String pwd = encodePassword("e10adc3949ba59abbe56e057f20f883e", salt);
        System.out.println("pwd=======" + pwd);
    }

}
